<template>
  <div style="height: 100%">
    <mTableLayout>
      <template #op-btn>
        <!-- 新增 删除 -->
        <el-button
          v-if="isCreate == 1"
          type="primary"
          @click="handleAdd()"
          icon="Plus"
          >新增</el-button
        >
        <el-button
          v-if="isDelete == 1"
          type="danger"
          @click="batchDelete"
          :disabled="selectionData.length === 0"
          icon="Delete"
          >删除</el-button
        >
      </template>
      <template #table>
        <mTable
          ref="mTableRef"
          :tableHeader="tableHeader"
          :tableData="tableData"
          :adapter="tableAjax"
          @selection-change="handleSelectionChange"
        >
          <template #handle="{ row }">
            <el-button
              v-if="isAuth == 1"
              type="primary"
              link
              @click="handleAssignProject(row)"
            >
              授权
            </el-button>
          </template>
          <template #default="{ row }">
            <img
              v-if="isEdit == 1"
              @click="handleEdit(row)"
              src="@/assets/images/icon/update_icon.png"
              class="update_icon"
            />
            <img
              v-if="isDelete == 1 && row.id != 1"
              @click="handleDelete(row.id)"
              src="@/assets/images/icon/delete_icon.png"
              class="delete_icon"
            />
          </template>
        </mTable>
      </template>
    </mTableLayout>

    <el-dialog
      v-model="updateVisible"
      :title="updateForm.id ? '修改角色' : '新增角色'"
      width="500px"
    >
      <el-form
        :model="updateForm"
        :rules="updateRules"
        ref="formRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="updateForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            type="textarea"
            v-model="updateForm.description"
            placeholder="请输入角色描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="updateVisible = false">取消</el-button>
          <el-button type="primary" @click="saveUpdate"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 指派项目 -->
    <Assign ref="assignRef" @refresh="mTableRef.fetchData(true)" />
    <!-- 角色表单（新增/编辑） -->
    <AddRole ref="addRoleRef" @refresh="mTableRef.fetchData(true)" />
  </div>
</template>
<script setup>
import { tableHeader, formConfigs } from "./config";

import { ref, onMounted, reactive } from "vue";
import Assign from "./assign.vue";
import AddRole from "./addRole.vue";

import { rolesList, addRole, updateRole, deleteRole } from "@/api";
import { ElMessage, ElMessageBox } from "element-plus";
import { useAppStore } from "@/stores/app.js";

const formInline = reactive({
  name: "",
});

const onSearch = (data) => {
  console.log(data.value);
  // formInline = data.value;
  mTableRef.value.fetchData(true);
};

const mTableRef = ref(null);
const total = ref(0);
const updateVisible = ref(false);
const assignRef = ref(null);
const addRoleRef = ref(null);
const appStore = useAppStore();
const isCreate = ref(null);
const isDelete = ref(null);
const isEdit = ref(null);
const isAuth = ref(null);

const updateForm = ref({
  id: null,
  name: null,
});
const updateRules = ref({
  name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
  description: [{ required: true, message: "请输入角色描述", trigger: "blur" }],
  // person: [{ required: true, message: "请输入组织负责人", trigger: "blur" }],
});
const selectionData = ref([]);

const tableData = ref([]);
onMounted(() => {
  if (appStore.userInfo?.roles?.role_manage?.indexOf("create") >= 0) {
    isCreate.value = 1;
  } else {
    isCreate.value = 0;
  }

  if (appStore.userInfo?.roles?.role_manage?.indexOf("edit") >= 0) {
    isEdit.value = 1;
  } else {
    isEdit.value = 0;
  }

  if (appStore.userInfo?.roles?.role_manage?.indexOf("delete") >= 0) {
    isDelete.value = 1;
  } else {
    isDelete.value = 0;
  }

  if (appStore.userInfo?.roles?.role_manage?.indexOf("auth") >= 0) {
    isAuth.value = 1;
  } else {
    isAuth.value = 0;
  }

  mTableRef.value.fetchData(true);
});
// 列表请求
const tableAjax = async ({ pageSize, currentPage }) => {
  let o = {
    pageSize,
    page: currentPage,
    ...formInline,
  };
  let res = await rolesList(o);
  console.log(res, "res");
  if (res.code == 0) {
    tableData.value = res.data;
    total.value = res.count || 0;
  }
  return {
    data: res.data,
    total: res.count || 0,
  };
};

const handleAssignProject = (row) => {
  console.log(row);
  assignRef.value.openDrawer(row);
};

const handleAdd = () => {
  addRoleRef.value.openAddDrawer();
};

const handleEdit = (row) => {
  addRoleRef.value.openEditDrawer(row);
};

const handleUpdate = (row) => {
  if (row) {
    updateForm.value = { ...row };
  } else {
    updateForm.value = {
      id: null,
      name: null,
      description: null,
    };
  }
  updateVisible.value = true;
};

const batchDelete = () => {
  handleDelete(selectionData.value.map((item) => item.id).join(","));
};

// 批量+单个处理删除
const handleDelete = (ids) => {
  ElMessageBox.confirm("确定删除吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deleteRole({ id: ids }).then((res) => {
      if (res.code == 0) {
        mTableRef.value.fetchData(true);
        ElMessage.success("删除成功");
      }
    });
  });
};

const saveUpdate = () => {
  console.log(updateForm.value);
  if (updateForm.value.id) {
    updateRoleFun(updateForm.value);
  } else {
    addRoleFun(updateForm.value);
  }
};
const updateRoleFun = (data) => {
  let o = {
    id: data.id,
    name: data.name,
    description: data.description,
  };
  updateRole(o).then((res) => {
    if (res.code == 0) {
      updateVisible.value = false;
      mTableRef.value.fetchData(true);
      ElMessage.success("修改成功");
    }
    console.log(res);
  });
};
const addRoleFun = (data) => {
  console.log(data);
  addRole(data).then((res) => {
    if (res.code == 0) {
      updateVisible.value = false;
      mTableRef.value.fetchData(true);
      ElMessage.success("新增成功");
    }
  });
};
// 页面上勾选的数据选择
const handleSelectionChange = (val) => {
  selectionData.value = val;
};
</script>
<style scoped lang="scss">
:deep(.demo-form-inline) {
  .el-input,
  .el-select {
    width: 220px;
  }
}
</style>
